import {CascadePicker} from "antd-mobile";
import {CascadePickerOption} from "antd-mobile/es/components/cascade-picker";
import {PickerProps} from "antd-mobile/es/components/picker";
import {useEffect, useState} from "react";
import {fetchStation} from "./http/StationController";

type StationPickerProps = Omit<PickerProps, "columns">

const StationPicker = (props: StationPickerProps)=>{
    const [options, setOptions] = useState<CascadePickerOption[]>([]);

    useEffect(()=>{
        fetchStation()
            .then(async (res)=>{
                if (options.length > 0) return;
                const _options = res.reduce((prev:any, curr:any, index: number)=>{
                    for (const re of res.slice(index+1)) {
                        if (curr.city === re.city) return prev;
                    }
                    prev.push({
                        label: curr.city,
                        value: curr.city
                    });
                    return prev;
                }, []);
                _options.forEach((v: any)=>{
                    v.children = [];
                    for (const re of res) {
                        if (re.city === v.label){
                            v.children.push({
                                label: re.name,
                                value: re.name
                            });
                        }
                    }
                });
                setOptions(_options);
            });
    });

    return (
        <CascadePicker options={options}
                       {...props}
        />
    );
}

export default StationPicker;
